package com.android.lovely.ui.activity

import android.Manifest
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isGone
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ConcatAdapter
import com.android.lovely.R
import com.android.lovely.api.service.upload
import com.android.lovely.api.service.userService
import com.android.lovely.databinding.ActivityRechargeBackBinding
import com.android.lovely.ext.windowBackgroundNav
import com.android.lovely.ext.windowBackgroundStatus
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.ui.adapter.ItemAddAdapter
import com.android.lovely.ui.adapter.ItemOrderAdapter
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll

class RechargeBackActivity : BaseActivity<ActivityRechargeBackBinding>() {

    private val cardAdapter by lazy {
        ItemOrderAdapter().apply {
            onItemClick = { _, _ ->
                concatAdapter.addAdapter(0, addAdapter)
                checkContent()
            }
        }
    }

    private val concatAdapter = ConcatAdapter()

    private val addAdapter by lazy {
        ItemAddAdapter().apply {
            onItemClick = {
                addCard()
            }
        }
    }

    private val botId: Int by lazy { intent.getIntExtra("bot_id", 0) }

    private val storagePermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                imageLauncher.launch("image/*")
            }
        }


    private val imageLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
            uri?.let {
                cardAdapter.insert(it)
                checkContent()
                if (cardAdapter.itemCount >= 4) {
                    concatAdapter.removeAdapter(addAdapter)
                }
            }
        }

    override fun initView(savedInstanceState: Bundle?) {
       mBinding.toolbar.addStatusBarMarginTop()
        concatAdapter.addAdapter(addAdapter)
        concatAdapter.addAdapter(cardAdapter)
        mBinding.shots.adapter = concatAdapter
        mBinding.back.clickable { onBackPressedDispatcher.onBackPressed() }
        mBinding.number.doAfterTextChanged {
            checkContent()
        }
        mBinding.content.doAfterTextChanged {
            mBinding.contentNum.text = "${(it?.length ?: 0)}/800"
        }
        mBinding.email.doAfterTextChanged {
            mBinding.mailNum.text = "${(it?.length ?: 0)}/100"
        }
        mBinding.submit.clickable {
            commit()
        }
    }

    private fun commit() {
        lifecycleScope.launchWithLoading {
            val urls: List<String> = cardAdapter.getItems().map { async(Dispatchers.IO) { it.upload() } }.awaitAll()
            if (urls.all { it.isEmpty() }) {
                showToast(getString(R.string.report_failure))
                return@launchWithLoading
            }
            userService.reportV2(buildParams(urls))
            showToast(getString(R.string.report_success))
            finish()
        }.onError {
            showToast(getString(R.string.report_failure))
        }
    }

    private fun buildParams(urls: List<String>) = mapOf(
        "bot_id" to botId,
        "apple_order_id" to mBinding.number.text.toString(),
        "detail" to mBinding.content.text.toString(),
        "type" to 2,
        "reason_id" to 9,
        "email" to mBinding.email.text.toString(),
        "image_list" to urls
    )

    private fun addCard() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            imageLauncher.launch("image/*")
        } else {
            storagePermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }

    private fun checkContent() {
        mBinding.disable.isGone = cardAdapter.itemCount > 0 && mBinding.number.text.isNullOrBlank().not()
    }
}